function [ tau_list,C_list,error_found ] = CrossValidation( X,t,N )
% CrossValidation Algorithm for finding the correct parameters of SVM
%
% INPUT:
% X			-- Data
% t			-- Label (double)
% N			-- Number of subdivision for CrossValidation
%
% OUTPUT:
% tau_list  -- tau values
% C_list    -- C values
% error_found -- corresponding error(i_tau,i_C)
%
% USAGE:
% [ tau_list,C_list,error_found ] = CrossValidation( X,t,N )

[n,d]=size(X);

%% Initialize tau_list and c_list
%tau_list=0.001*2.^(0:9);
%C_list=65.536*2.^(0:9);

tau_list=0.0016*2.^(0:9);
C_list=65.536*2.^(0:9);

n_tau=length(tau_list);
n_C=length(C_list);

set_size=round(n/N);

error_found=zeros(n_tau,n_C);


for i_tau=1:n_tau
	%% Computation of the whole kernel for efficiency
	D=sum(X.*X,2);
	Ones_n=ones(1,n);
	A=0.5*D*Ones_n + 0.5*Ones_n'*D' - X*X';
	K=exp(-tau_list(i_tau)*A);

	for i_C=1:n_C
        fprintf('Tau = %f , C = %f \n',tau_list(i_tau),C_list(i_C));
		%% Cross Validation estimator
		error=0;
        for i_set=1:N
            validation_indices=(i_set-1)*set_size+1:i_set*set_size;
            training_indices=[1:(i_set-1)*set_size , i_set*set_size+1:n];
            %% Partial training
            [alpha,b]=SMO(K(training_indices,training_indices),t(training_indices),C_list(i_C));
            %% Partial estimator
            y=K(validation_indices,training_indices)*(alpha.*t(training_indices))-b;
            error=error+sum(max(0,1-y.*t(validation_indices)));
        end
        fprintf('Error = %f \n',error/n);
		error_found(i_tau,i_C)=error/n;	
	end
end


end

